﻿using System;
using System.Collections.Generic;
using System.Text;

namespace LeetcodeTest._100._30
{
    public class Leetcode25
    {
        public class ListNode
        {
            public int val;
            public ListNode next;
            public ListNode(int x) { val = x; }
        }
        /*
         25. Reverse Nodes in k-Group 

         Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5 
         */

        public ListNode ReverseKGroup(ListNode head, int k)
        {
            if (head == null || head.next == null || k == 1)
                return head;

            ListNode tempNode = head;
            ListNode mainNode = head;
            int nodeCount = 0;
            while (tempNode != null)
            {
                nodeCount++;
                if (nodeCount == k)
                {
                    SwapNodes(mainNode, k);
                    mainNode = tempNode.next;
                    nodeCount = 0;
                }
                tempNode = tempNode.next;

            }
            return head;
        }

        private void SwapNodes(ListNode head, int k)
        {
            int tempNodeValue = head.val;
            ListNode tempNode1, tempNode2;
            for (int i = 0; i < k / 2; i++)
            {
                tempNode1 = GetNodeByIndex(head, i);
                tempNode2 = GetNodeByIndex(head, k - i - 1);
                tempNodeValue = tempNode1.val;
                tempNode1.val = tempNode2.val;
                tempNode2.val = tempNodeValue;
            }

        }

        private ListNode GetNodeByIndex(ListNode head, int index)
        {
            ListNode tempNode = head;
            for (int i = 1; i <= index; i++)
            {
                tempNode = tempNode.next;
            }
            return tempNode;
        }
    }
}
